<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\JsonResponse;


use AppBundle\Entity\Task;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

class ControllerController extends Controller
{

    // 1返回一个json信息
    /**
     * @Route("/controller/show/{max}", name="controller_show", requirements={"max": "\d+"})
     */
    public function showAction(Request $request,$max = 1)
    {

        //返回json
        $number = mt_rand(0, $max);
        return new Response(
            '<html><body>controllercontroller-showAction: '.$number.'</body></html>'
        );

    }


    // 2重定向
    /**
     * @Route("/chongdingxiang/show", name="chongdingxiang_show", requirements={"max": "\d+"})
     */
    public function chongdingxiangAction(Request $request,$max = 1)
    {



        // redirect to the "homepage" route
        return $this->redirectToRoute('homepage');

        // do a permanent - 301 redirect
        return $this->redirectToRoute('homepage', array(), 301);

        // redirect to a route with parameters
        return $this->redirectToRoute('homepage', array('slug' => 'my-page'));

        // redirect externally
        return $this->redirect('http://symfony.com/doc');


        return new RedirectResponse($this->generateUrl('homepage'));



        //渲染模板
        return $this->render('test/ControllerController-chongdingxiangAction.html.twig', array('name' => $name));
    }

    // 3渲染模板
    /**
     * @Route("/render/show", name="render_show", requirements={"max": "\d+"})
     */
    public function renderShowAction(Request $request,$max = 1)
    {

        //渲染模板
        return $this->render('test/ControllerController-renderAction.html.twig', array('name' => 'yuegang'));
    }


    // 4访问其他服务
    /**
     * @Route("/get/other", name="get_other_show", requirements={"max": "\d+"})
     */
    public function getOtherAction(Request $request,$max = 1)
    {

        $templating = $this->get('templating');
        $router = $this->get('router');
        $mailer = $this->get('mailer');

        // 获取 parameter 问
        $from = $this->getParameter('database_host');

        echo '<pre>';
        @print_r( $from    );
        exit;
    }


    // 5获取配置信息
    /**
     * @Route("/getparameter", name="getparameter", requirements={"max": "\d+"})
     */
    public function getparameterAction(Request $request,$max = 1)
    {

        // 获取 parameter 配置信息
        $from = $this->getParameter('database_host');
    }


    // 6管理错误和404页
    /**
     * @Route("/manager404page", name="manager404page", requirements={"max": "\d+"})
     */
    public function manager404pageAction(Request $request,$max = 1)
    {
        $product = '';
        if (!$product) {
            throw $this->createNotFoundException('this is The product does not exist');
        }
    }


    // 7管理错误和500页
    /**
     * @Route("/manager500page", name="createjsonObjectArray", requirements={"max": "\d+"})
     */
    public function createjsonObjectArrayAction(Request $request,$max = 1)
    {

        throw new \Exception('Something went wrong!');

    }


    // 8 request获取参数
    /**
     * @Route("/getreqeustjqueryget", name="getreqeustjqueryget", requirements={"max": "\d+"})
     */
    public function getreqeustjquerygetAction(Request $request,$max = 1)
    {
        $page = $request->query->get('page', 1);
        echo $page;
        exit;
    }



    // 9 回话管理 - 1 设置
    /**
     * @Route("/getSession", name="getSession", requirements={"max": "\d+"})
     */
    public function getSessionAction(Request $request)
    {
        $session = $request->getSession();



        // store an attribute for reuse during a later user request
        $session->set('foobar', '鸟毛');


        // get the attribute set by another controller in another request
        $foobar = $session->get('foo');


        // use a default value if the attribute doesn't exist
        $filters = $session->get('filters', array());
        exit;
    }


    // 9 回话管理 - 2 获取属性
    /**
     * @Route("/getSession2", name="getSession2", requirements={"max": "\d+"})
     */
    public function getSession2Action(Request $request)
    {
        $session = $request->getSession();

        // store an attribute for reuse during a later user request
        $session->set('foo', 'bar');


        // get the attribute set by another controller in another request
        $foobar = $session->get('foobar');

        echo $foobar;
        echo "\n";


        // use a default value if the attribute doesn't exist
        $filters = $session->get('filters', array());


        echo '<pre>';
        @print_r( $filters    );
        exit;

    }



    // 10 flash信息
    /**
     * @Route("/flash", name="flash", requirements={"max": "\d+"})
     */
    public function flashAction(Request $request)
    {

        $this->addFlash(
                'bb',
                'bb  message!'
            );

        $this->addFlash(
                'notice',
                'notice message!'
            );

        return $this->render('test/ControllerController-flashAction.html.twig', array(

        ));



    }


    // 11 form
    /**
     * @Route("/form", name="form", requirements={"max": "\d+"})
     */
    public function formAction(Request $request)
    {

        $task = new Task();
        $task->setTask('Write a blog post');
        $task->setDueDate(new \DateTime('tomorrow'));

        $form = $this->createFormBuilder($task)
            ->add('task', TextType::class)
            ->add('dueDate', DateType::class)
            ->add('save', SubmitType::class, array('label' => 'Create Post'))
            ->getForm();

        if ($form->isSubmitted() && $form->isValid()) {
            $this->addFlash(
                'notice',
                'Your changes were saved!'
            );

        }


        return $this->render('test/ControllerController-formAction.html.twig', array(
            'form' => $form->createView(),
        ));



    }




    // 11 form
    /**
     * @Route("/requestResponse", name="requestResponse", requirements={"max": "\d+"})
     */
    public function requestResponseAction(Request $request)
    {

        $request->isXmlHttpRequest(); // is it an Ajax request?

       $request->getPreferredLanguage(array('en', 'fr'));

       // retrieve GET and POST variables respectively
       $request->query->get('page');
       $request->request->get('page');

       // retrieve SERVER variables
       $request->server->get('HTTP_HOST');

       // retrieves an instance of UploadedFile identified by foo
       $request->files->get('foo');

       // retrieve a COOKIE value
       $request->cookies->get('PHPSESSID');

       // retrieve an HTTP request header, with normalized, lowercase keys
       $request->headers->get('host');
       $request->headers->get('content_type');

       $name = 'yuegang';
       $response = new Response('Hello '.$name, Response::HTTP_OK);

       // 1
       // return $response;






       // 2
       // create a CSS-response with a 200 status code
       $response = new Response('<style> ... </style>');
       $response->headers->set('Content-Type', 'text/css');

       return $response;

    }




    // 12 json帮助 3.1版本才有
    /**
     * @Route("/jsonhelp", name="jsonhelp", requirements={"max": "\d+"})
     */
    public function jsonhelpAction(Request $request)
    {
        return $this->json(array('username' => 'jane.doe'),200);

    }



    // 12 file帮助 3.2版本才有
    /**
     * @Route("/filehelp", name="filehelp", requirements={"max": "\d+"})
     */
    public function filehelpAction(Request $request)
    {

        $rootDirectory = dirname($this->getParameter('kernel.root_dir'));
        $file          = "{$rootDirectory}/app/data/1mpdf.pdf";


        //在线预览
        return $this->file($file, 'my_invoice.pdf', ResponseHeaderBag::DISPOSITION_INLINE);

        //直接下载
        return $this->file($file);

        //直接下载 给予指定的名字
        return $this->file($file, 'custom_name.pdf');


        //不能直接下载第三方地址的pdf
        return $this->file('http://7xorxy.com2.z0.glb.qiniucdn.com/2016/0302/7258d6c191204f56a4b00a4680534fdd.pdf');

    }



    // 13 twig操作
    /**
     * @Route("/twigtest", name="twigtest", requirements={"max": "\d+"})
     */
    public function twigtestAction(Request $request)
    {

        $page_title = '时间symfony的页面';
        $navigation = [
            ['caption'=>'百度','href'=>'http://www.baidu.com'],
            ['caption'=>'网易','href'=>'http://www.163.com']
        ];

        //渲染模板
        return $this->render('test/ControllerController-twighelpAction.html.twig',[
            'page_title' => $page_title,
            'navigation' => $navigation
        ]);

    }


    // 13 twig - 过滤器操作
    /**
     * @Route("/twigguolvqi", name="twigguolvqi", requirements={"max": "\d+"})
     */
    public function twigguolvqiAction(Request $request)
    {

        $title = '将数据的内容以大写的方式呈现 比如说 :  abc';

        //渲染模板
        return $this->render('test/ControllerController-twigguolvqiAction.html.twig',[
            'title' => $title,
        ]);

    }


    // 13 twig - 循环
    /**
     * @Route("/twigxunhuan", name="twigxunhuan", requirements={"max": "\d+"})
     */
    public function twigxunhuanAction(Request $request)
    {

        $title = '循环周期数据,判断是偶数还是奇数';

        //渲染模板
        return $this->render('test/ControllerController-twigxunhuanAction.html.twig',[
            'title' => $title,
        ]);

    }


    // 14 twig - 循环判断
    /**
     * @Route("/twigxunhuanpanduan", name="twigxunhuanpanduan", requirements={"max": "\d+"})
     */
    public function twigxunhuanpanduanAction(Request $request)
    {
        $users = [
            ['username'=>'岳刚','active'=>'1'],
            ['username'=>'王建刚'],
            ['username'=>'会亮','active'=>'1'],
            ['username'=>'羊羊','active'=>'1'],
            ['username'=>'毛毛','active'=>'1'],
        ];
        $title = '循环周期数据,判断是偶数还是奇数';

        //渲染模板
        return $this->render('test/ControllerController-twigxunhuanpanduanAction.html.twig',[
            'title' => $title,
            'users' => $users
        ]);

    }




    // 14 twig - 模板继承
    /**
     * @Route("/twigjichenglayout", name="twigjichenglayout", requirements={"max": "\d+"})
     */
    public function twigjichenglayoutAction(Request $request)
    {
        $users = [
            ['username'=>'岳刚','active'=>'1'],
            ['username'=>'王建刚'],
            ['username'=>'会亮','active'=>'1'],
            ['username'=>'羊羊','active'=>'1'],
            ['username'=>'毛毛','active'=>'1'],
        ];
        $title = '循环周期数据,判断是偶数还是奇数';

        //渲染模板
        return $this->render('test/twigjichengAction/ControllerController-twigjichenglayoutAction.html.twig',[
            'title' => $title,
            'users' => $users
        ]);

    }


    // 15 twig - 使用 - 模板继承
    /**
     * @Route("/twigshiyongjichenglayout", name="twigshiyongjichenglayout", requirements={"max": "\d+"})
     */
    public function twigshiyongjichenglayoutAction(Request $request)
    {
        $users = [
            ['username'=>'岳刚','active'=>'1'],
            ['username'=>'王建刚'],
            ['username'=>'会亮','active'=>'1'],
            ['username'=>'羊羊','active'=>'1'],
            ['username'=>'毛毛','active'=>'1'],
        ];
        $title = '继承模板';

        //渲染模板
        return $this->render('test/twigjichengAction/ControllerController-twigshiyongjichenglayoutAction.html.twig',[
            'title' => $title,
            'users' => $users
        ]);

    }



    // 15 twig -
    //      渲染指定名称url
    //      渲染绝对url
    //      渲染绝对logo
    /**
     * @Route("/twigxuanranurl", name="twigxuanranurl", requirements={"max": "\d+"})
     */
    public function twigxuanranurlAction(Request $request)
    {
        $users = [
            ['username'=>'岳刚','active'=>'1'],
            ['username'=>'王建刚'],
            ['username'=>'会亮','active'=>'1'],
            ['username'=>'羊羊','active'=>'1'],
            ['username'=>'毛毛','active'=>'1'],
        ];
        $title = '继承模板';

        //渲染模板
        return $this->render('test/ControllerController-twigxuanranurlAction.html.twig',[
            'title' => $title,
            'users' => $users
        ]);

    }



    // 16 twig - include
    /**
     * @Route("/twiginclude", name="twiginclude", requirements={"max": "\d+"})
     */
    public function twigincludeAction(Request $request)
    {
        $users = [
            ['username'=>'岳刚','active'=>'1'],
            ['username'=>'王建刚'],
            ['username'=>'会亮','active'=>'1'],
            ['username'=>'羊羊','active'=>'1'],
            ['username'=>'毛毛','active'=>'1'],
        ];
        $title = '继承模板';

        //渲染模板
        return $this->render('test/ControllerController-twigincludeAction.html.twig',[
            'title' => $title,
            'users' => $users
        ]);

    }


    // 17 twig - 设置块区域
    /**
     * @Route("/shezhikuaiquyu", name="shezhikuaiquyu", requirements={"max": "\d+"})
     */
    public function shezhikuaiquyuAction(Request $request)
    {
        $users = [
            ['username'=>'岳刚','active'=>'1'],
            ['username'=>'王建刚'],
            ['username'=>'会亮','active'=>'1'],
            ['username'=>'羊羊','active'=>'1'],
            ['username'=>'毛毛','active'=>'1'],
        ];
        $title = '继承模板';

        //渲染模板
        return $this->render('test/setTagLayout/index.html.twig',[
            'title' => $title,
            'users' => $users
        ]);

    }

}
